#!/usr/bin/env python3
"""
Quick fix for malformed tables in LaTeX files
"""

import re
import os
from pathlib import Path

def fix_tables(content):
    """Remove malformed tables and fix basic issues"""
    
    # Remove malformed table structures
    # Look for sequences like \hline \hline with empty or malformed content
    content = re.sub(
        r'\\begin\{table\}\[H\]\s*\\centering\s*\\begin\{tabular\}\{[^}]*\}\s*\\hline\s*[^\\]*\\hline\s*\\hline\s*\\end\{tabular\}\s*\\end\{table\}',
        '',
        content,
        flags=re.MULTILINE | re.DOTALL
    )
    
    # Also remove any stray ```bash or ``` lines that weren't converted properly
    content = re.sub(r'^```\w*\s*$', '', content, flags=re.MULTILINE)
    content = re.sub(r'^```\s*$', '', content, flags=re.MULTILINE)
    
    # Fix any remaining double backslashes in texttt commands
    content = re.sub(r'\\texttt\{([^}]*)\}\\texttt\{([^}]*)\}', r'\\texttt{\1\2}', content)
    
    # Fix malformed texttt commands like \texttt{
    content = re.sub(r'\\texttt\{\s*$', '', content, flags=re.MULTILINE)
    
    # Remove any lines that are just "}" 
    content = re.sub(r'^\s*\}\s*$', '', content, flags=re.MULTILINE)
    
    return content

def fix_file(file_path):
    """Fix a single file"""
    print(f"Fixing {file_path}")
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        fixed_content = fix_tables(content)
        
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(fixed_content)
            
    except Exception as e:
        print(f"Error fixing {file_path}: {e}")

def main():
    """Fix all chapter files"""
    chapters_dir = Path("/home/linden/claude/packages/ccwork/claude-code-development-book/chapters")
    
    for tex_file in chapters_dir.glob("*.tex"):
        fix_file(tex_file)
    
    print("Table fixes complete!")

if __name__ == "__main__":
    main()